<?php
namespace Frieza\Modules\Decoration\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\service\Decoration\Main as sMain;
use Kafka\Exception;
use Doraemon\tools\LinkConf;

class AdvController extends Controller
{
    const PAGE_SIZE = 500;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }

        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function list(Request $request,Content $content, $parentId = 0, $sonId = 0, $sid = 0, $aid = 0){
        $requests = $request;
        if(strpos($requests->url(), '/decoration/subject/')){
            $sid = $parentId;
            $parentId = $sonId = $aid = 0;
        }
        $request = $request->all();
        $preUrl = '';
        $preUrl2 = '';
        $curUrl = '/admin/decoration';
        if($parentId > 0){
            $request['rela_id'][0] = $parentId;
            $preUrl = '/decoration/category/'.$parentId.'/edit';
            $curUrl.= '/category/'.$parentId.'/edit';
        }
        if($sonId > 0){
            $request['rela_id'][1] = $sonId;
            $preUrl = $preUrl. '/' .$sonId.'/edit';
            $curUrl.= '/' . $sonId . '/edit';
        }
        if($sid > 0){
            if(isset($request['rela_id'])) {
                $request['rela_id'] = $request['rela_id'][1];
            }
            $request['sid'] = $sid;
            $preUrl2 = $preUrl. '/subject/'.$sid.'/edit';
            $curUrl.= '/subject/'.$sid.'/adv/create';
        }else{
            $request['rela_id'] = $request['rela_id'][0];
            $curUrl.= '/adv/create';
        }
        if($aid > 0){
            $request['id'] = $aid;
            $preUrl2 = $preUrl. '/adv/'.$aid.'/edit';
            $curUrl.= '/'.$aid.'/edit';
        }
        if(!empty($preUrl)){
            $preUrl = ['text' => '上级分类', 'url' => $preUrl];
        }
        if(!empty($preUrl2)){
            $preUrl2 = ['text' => '上级主题', 'url' => $preUrl2];
        }
        $request = self::_filterWhere($request);$tab = new Tab();
        $tab->add('资源列表', self::listAction($request));
        if(strpos($requests->url(), 'edit', '-4')) {
            $tab->addLink('编辑资源位', $curUrl);
        }else{
            $tab->addLink('创建资源位', $curUrl);
        }

        if(!empty($preUrl)) {
            if(!empty($preUrl2)){
                return $content
                    ->header('资源列表')
                    ->breadcrumb(
                        $preUrl,
                        $preUrl2,
                        ['text' => '资源列表']
                    )
                    ->body($tab);
            }else {
                return $content
                    ->header('资源列表')
                    ->breadcrumb(
                        $preUrl,
                        ['text' => '资源列表']
                    )
                    ->body($tab);
            }
        }else{
            return $content
                ->header('资源列表')
                ->breadcrumb(
                    ['text' => '上级主题', 'url' => '/decoration/subject/create'],
                    ['text' => '资源列表']
                )
                ->body($tab);
        }
    }

    public function listAction($request = []){

        $tab = new Tab();

       $tab->add('全部资源位', self::getShowtype($request, 0));
        foreach(mAdv::SHOW_TYPE as $_sk=>$_sv) {
            $tab->add($_sv, self::getShowtype($request, $_sk));
        }

        return $tab->render();
    }

    public function getShowtype($request, $showType = 0){
        if(isset($request['AND']['rela_id']) && !isset($request['AND']['id'])){
            $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$request['AND']['rela_id'].',rela_id)';
            $relaId = mAdv::query($sql)->fetchAll();
            $request['AND']['id'] = array_column($relaId, 'id');
            unset($request['AND']['rela_id']);
        }
        if($showType>0) {
            $request['AND']['show_type'] = $showType;
        }
        if(empty($request['AND'])){
            unset($request['AND']);
        }

        $data = sMain::getAdv($request);

        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($showType) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();

            if($showType>0){
                $grid->disableFilter();
            }else {
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('date_time', '资源时间')->datetime()->condition($_GET);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('show_type', '资源位置')->select(mAdv::SHOW_TYPE);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('name', '名称')->placeholder('请输入名称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('group_title', '内容卡片标题')->placeholder();
                    });
                });
                $grid->fixColumns(0, -1);
            }

            $grid->column('id')->sort();;
            $grid->column('rela_name', '关联分类');
            $grid->column('sid_name', '关联主题');
            $grid->column('show_type', '资源位置')->display(function(){
                return mAdv::SHOW_TYPE[$this->show_type];
            });
            $grid->column('name', '名称')->display(function(){
                if(!empty($this->name)) {
                    return '<p style="color:' . $this->font_color . ';">' . $this->name . '</p>';
                }else{
                    return '<p style="color:' . $this->font_color . ';">暂空</p>';
                }

            });
            $grid->column('group_title', '内容卡片');
            $grid->column('is_point', '背景是否透明')->display(function(){
                if($this->is_point) {
                    return '是';
                }else{
                    return '否';
                }
            });
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('sort', '权重');

            if (in_array($showType, [4012, 4013])) {
                $grid->column('pos', '位置');
                $grid->column('obj_id', '内容/wiki id');
            }

            if($showType > 0) {
                $grid->column('link', '链接')->limit(30);
            }else {
                $grid->column('link', '链接信息')->linkSelect();
            }

            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();

                if($actions->row->status >= 2) {
                    $actions->disableEdit();
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function sort(Request $request){
        $params = $request->all();

        $result = mAdv::action(function()use($params){
            foreach($params['sort'] as $_k=>&$_v){
                if(!mAdv::updateData(['sort' => $_v], ['id' => $_k])){
                    return false;
                }
            }
            return true;
        });

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }

    public static function save(Request $request, $parentId = 0, $sonId = 0, $sid = 0, $id = 0)
    {
        if(strpos($request->url(), '/decoration/subject/')){
            $sid = $parentId;
            $id = $sonId;
            $parentId = $sonId = 0;
        }
        $preUrl = '/admin/decoration';
        if($parentId > 0){
            $preUrl.= '/category/'.$parentId.'/edit';
        }
        if($sonId > 0){
            $preUrl.=  '/' .$sonId.'/edit';
        }
        if($sid > 0){
            $preUrl.= '/subject/'.$sid.'/adv';
        }

        $get = $_SERVER["QUERY_STRING"];
        $params = $request->all();
        if(isset($params['id']) && $params['id'] > 0 && !isset($params['name'])){
            $param = [
                'link_type'=> $params['link_type'],
                'link_params'=> json_encode($params['link_params'], true),
                //'link_url'=> $params['link_url'],
                'link'=> $params['link_url'],
                'admin_id' => Admin::user()->id,
            ];
            $result = mAdv::updateData($param,['id'=>$params['id']]);
        }else {

            if (in_array($params['show_type'], [mAdv::SHOW_TYPE_2, mAdv::SHOW_TYPE_4])) {
                $where = [
                    'show_type' => $params['show_type'],
                    'sort' => $params['sort'],
                    'sort[>]' => 0,
                    'status[<]' => mAdv::STATUS_CLOSE,
                ];
                if (isset($request['id'])) {
                    $where['id[!]'] = $params['id'];
                }
//                if (mAdv::getOneByWhere($where, 'id')) {
//                    $error = new MessageBag([
//                        'title' => '权重不能重复'
//                    ]);
//
//                    return back()->with(compact('error'));
//                }
            }
            if (in_array($params['show_type'], [4012, 4013])) {
                if (empty($params['pos']) || empty($params['obj_id'])) {
                    $error = new MessageBag([
                        'title' => '位置必须大于0或者内容id必填'
                    ]);

                    return back()->with(compact('error'));
                }
            }
            if (!in_array($params['show_type'], [4012, 4013]) && (!isset($params['id']) && empty($params['link_params']))) {
                $error = new MessageBag([
                    'title' => '链接不能为空'
                ]);

                return back()->with(compact('error'));
            }

            if ($params['category_1']) {
                $params['category_1'] = array_filter($params['category_1']);
                if (!empty($params['category_1'])) {
                    $params['rela_id'] = implode(',', $params['category_1']);
                }
                unset($params['category_1']);
            }
            if ($params['category_2']) {
                $params['category_2'] = array_filter($params['category_2']);
                if (!empty($params['category_2'])) {
                    $params['rela_id'] = implode(',', $params['category_2']);
                }
                unset($params['category_2']);
            }

            if (empty($params['rela_id']) && empty($params['sid'])) {
                $error = new MessageBag([
                    'title' => '分类或者主题不能为空'
                ]);

                return back()->with(compact('error'));
            }
            if (empty($params['sid']) && empty($params['name'])) {
                $error = new MessageBag([
                    'title' => '名称不能为空'
                ]);

                return back()->with(compact('error'));
            }
            if (!empty($params['rela_id'])) {
                $category = mCategory::getAllByWhere(['id' => explode(',', $params['rela_id'])]);
                $category = array_column($category, 'is_cover');
                $category = array_filter($category);
                if (!empty($category) && empty($params['pic_id'])) {
                    $error = new MessageBag([
                        'title' => '关联的分类需要上传封面'
                    ]);

                    return back()->with(compact('error'));
                }
            }
            if (in_array($params['show_type'], [mAdv::SHOW_TYPE_2, mAdv::SHOW_TYPE_3, mAdv::SHOW_TYPE_4]) && empty($params['pic_id'])) {
                $error = new MessageBag([
                    'title' => '没有上传封面'
                ]);

                return back()->with(compact('error'));
            }

            if ($params['show_type'] == mAdv::SHOW_TYPE_5) {
                if ($params['select_group'] == 1) {
                    //创建,名称不能重复
                    if (!empty($params['group_title1']) && mAdv::getOneByWhere(['status[!]' => mCategory::STATUS_DELETE, 'group_title' => $params['group_title1'],'sid'=>$params['sid']], 'id')) {
                        $error = new MessageBag([
                            'title' => '内容卡片已经存在'
                        ]);

                        return back()->with(compact('error'));
                    }
                    $params['group_title'] = $params['group_title1'];
                } else {
                    //选中
                    $groupTitle = mAdv::getAllByWhere(['status[!]' => mCategory::STATUS_DELETE, 'GROUP' => 'group_title'], ['group_title', 'sort', 'id']);
                    $groupTitleSorts = array_column($groupTitle, 'sort', 'group_title');
                    if (!empty($params['group_title2'])) {
                        $params['group_title'] = $params['group_title2'];
                        $params['sort'] = !empty($params['sort']) ? $params['sort'] : $groupTitleSorts[$params['group_title2']];
                    } else {
                        $params['sort'] = !empty($params['sort']) ? $params['sort'] : '';
                    }
                }
                if (empty($params['sort'])) {
//                    $error = new MessageBag([
//                        'title' => '内容卡片权重不能为空'
//                    ]);
//
//                    return back()->with(compact('error'));
                } else {
                    if (isset($params['id']) && !empty($params['group_title2'])) {
                        $groupId = mAdv::getAllByWhere(['status[!]' => mCategory::STATUS_DELETE, 'group_title' => $params['group_title2']], 'id');
                        if (!empty($groupId)) {
                            try {
                                mAdv::updateData(['sort' => $params['sort']], ['id' => $groupId]);
                            } catch (Exception $e) {
                                $error = new MessageBag([
                                    'title' => $e
                                ]);

                                return back()->with(compact('error'));
                            }
                        }
                    }
                }
            }

            $param = [
                'show_type' => $params['show_type'],
                'rela_id' => isset($params['rela_id']) ? $params['rela_id'] : '',
                'sid' => isset($params['sid']) ? $params['sid'] : 0,
                'name' => isset($params['name']) ? $params['name'] : '',
                'font_color' => isset($params['font_color']) ? $params['font_color'] : '',
                'group_title' => isset($params['group_title']) ? $params['group_title'] : '',
                'is_point' => isset($params['is_point']) ? $params['is_point'] : 0,
                'sort' => isset($params['sort']) ? $params['sort'] : 0,
                'link' => !empty($params['link_url']) ? $params['link_url'] : (isset($params['id']) ? $params['link'] : ''),
                'link_type'=> $params['link_type'],
                'link_params'=> json_encode($params['link_params'], true),
                //'link_url'=> $params['link_url'],
                'pic_id' => isset($params['pic_id']) ? $params['pic_id'] : '',
                'start_time' => $params['start_time'],
                'end_time' => $params['end_time'],
                'pos' => $params['pos'] ?? 0,
                'obj_id' => $params['obj_id'] ?? '',
                'admin_id' => Admin::user()->id,
            ];

            if (!isset($params['id'])) {
                $action = 'add';
                $param['add_time'] = date('Y-m-d H:i:s');
                $result = mAdv::addData($param);
                $param['id'] = $result;
            } else {
                $action = 'update';
                if($param['start_time'] <= date('Y-m-d H:i:s') && $param['end_time'] > date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_OPEN ;
                }else if($param['start_time'] > date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_NOPEN ;
                }else if($param['end_time'] <= date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_CLOSE ;
                }
                $result = mAdv::updateData($param, ['id' => $params['id']]);
                $param['id'] = $params['id'];
            }
        }

        if($result){
            sCache::checkAdv(true);

            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect($preUrl)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => '操作失败'
            ]);

            return back()->with(compact('error'));
        }

    }


    public function saveLink(Request $request, $parentId = 0, $sonId = 0, $sid = 0, $id = 0){
        $params = $request->all();
        if(strpos($request->url(), '/decoration/subject/')){
            $id = $sonId;
            $parentId = $sonId = 0;
        }else if(strpos($request->url(), 'edit/adv')){
            $id = $sid;
        }
        $param = [
            'link' => !empty($params['link_url']) ? $params['link_url'] : (isset($params['id']) ? $params['link'] : ''),
            'link_type'=> $params['link_type'],
            'link_params'=> json_encode($params['link_params'], true),
            'admin_id' => Admin::user()->id,
        ];

        $result = mAdv::updateData($param, ['id' => $id]);

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public static function del(Request $request, $parentId = 0, $sonId = 0, $sid = 0, $aid =0)
    {
        if(strpos($request->url(), '/decoration/subject/')){
            $aid = $sonId;
            $parentId = $sonId = 0;
        }
        $get = $_SERVER["QUERY_STRING"];
        $data = ['status'=>mAdv::STATUS_DELETE];
        if(strpos($request->url(), 'subject')){
           $result = mAdv::updateData($data, ['id'=>$aid]);
        }else{
            if($sonId > 0) {
                $result = mAdv::updateData($data, ['id' => $sonId]);
            }else{
                $result = mAdv::updateData($data, ['id' => $sid]);
            }
        }

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function index(Request $request,Content $content, $sid = 0){
        $request = $request->all();
        $request = self::_filterWhere($request);

        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $subjects = [];
        if (!empty($subject)) {
            foreach ($subject as &$_v) {
                if($sid) {
                    if ($sid == $_v['id']) {
                        $subjects[$_v['id']] = $_v['name'];
                        break;
                    }
                }else{
                    $subjects[$_v['id']] = $_v['name'];
                }
            }
        }

        return $content
            ->header('资源位')
            ->breadcrumb(
                ['text' => '主题', 'url' => '/decoration/index/2'],
                ['text' => '资源位', 'url' => '/decoration/adv']
            )
            //->body(self::advs($request, $subjects, $sid).self::advsList($request, $sid));
            ->body(self::advsList($request, $sid));
    }

    public function create(Request $request,Content $content, $parentId = 0, $sonId = 0, $sid = 0, $aid = 0){
        if(strpos($request->url(), '/decoration/subject/')){
            $sid = $parentId;
            $aid = $sonId;
            $parentId = $sonId = 0;
        }
        $requests = $request;
        $request = $request->all();
        $preUrl = '';
        $preUrl2 = '';
        $preUrl3 = '';
        if($parentId > 0){
            $preUrl = '/decoration/category/'.$parentId.'/edit';
        }
        if(!strpos($requests->url(), 'subject')){
            //$request['rela_id'] = $sonId;
            $preUrl = $preUrl. '/' .$sonId.'/edit';
        }
        if($sid > 0){
            $preUrl2 = $preUrl. '/subject/'.$sid.'/edit';
        }
        if(strpos($requests->url(), 'subject')) {
            if($sid > 0) {
                $request['sid'] = $sid;
            }
            $preUrl3= $preUrl . '/subject/' . $sid . '/adv';
        }else {
            if($sid > 0) {
                $request['id'] = $sid;
            }
            $preUrl3 = $preUrl . '/adv';
            $sid = 0;
        }
        if($aid > 0){
            $request['id'] = $aid;
            $preUrl2 = $preUrl. '/adv/'.$aid.'/edit';
        }
        if(!empty($preUrl)){
            $preUrl = ['text' => '上级分类', 'url' => $preUrl];
        }
        if(!empty($preUrl2)){
            $preUrl2 = ['text' => '上级主题', 'url' => $preUrl2];
        }
        if(empty($preUrl) && !empty($preUrl3) && !strpos($preUrl3, '/decoration')){
             $preUrl3  = '/decoration'.$preUrl3;
        }

        $request = self::_filterWhere($request);

        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $subjects = [];

        if (!empty($subject)) {
            foreach ($subject as &$_v) {
                if($sid) {
                    if ($sid == $_v['id']) {
                        $subjects[$_v['id']] = $_v['name'];
                        break;
                    }
                }else{
                    $subjects[$_v['id']] = $_v['name'];
                }
            }
        }

        $tab = new Tab();
        if(strpos($requests->url(), 'edit', '-4')) {
            $tab->add('编辑资源位', self::advs($request, $subjects, [$parentId, $sonId], $sid, '/admin'.$preUrl3.'/save'));
        }else{
            $tab->add('创建资源位', self::advs($request, $subjects, [$parentId, $sonId], $sid,  '/admin'.$preUrl3.'/save'));
        }

        $tab->addLink('资源位列表','/admin'.$preUrl3);

        if(!empty($preUrl)) {
            if(!empty($preUrl2)) {
                return $content
                    ->header('资源列表')
                    ->breadcrumb(
                        $preUrl,
                        $preUrl2,
                        ['text' => '资源位列表', 'url' => $preUrl3],
                        ['text' => '基本信息']
                    )
                    ->body($tab);
            }else{
                return $content
                    ->header('资源列表')
                    ->breadcrumb(
                        $preUrl,
                        ['text' => '资源位列表', 'url' => $preUrl3],
                        ['text' => '基本信息']
                    )
                    ->body($tab);
            }
        }else{
            return $content
                ->header('资源列表')
                ->breadcrumb(
                    ['text' => '资源位列表', 'url' => $preUrl3],
                    ['text' => '基本信息']
                )
                ->body($tab);
        }
    }

    public function create2(Request $request,Content $content, $sid = 0){
        $request = $request->all();
        $request = self::_filterWhere($request);

        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $subjects = [];
        if (!empty($subject)) {
            foreach ($subject as &$_v) {
                if($sid) {
                    if ($sid == $_v['id']) {
                        $subjects[$_v['id']] = $_v['name'];
                        break;
                    }
                }else{
                    $subjects[$_v['id']] = $_v['name'];
                }
            }
        }

        return $content
            ->header('新增资源位')
            ->breadcrumb(
                ['text' => '主题', 'url' => '/decoration/index/2'],
                ['text' => '资源位列表', 'url' => '/decoration/adv/'.$sid],
                ['text' => '资源位', 'url' => '/decoration/adv']
            )
            //->body(self::advs($request, $subjects, $sid).self::advsList($request, $sid));
            ->body(self::advs($request, $subjects, $sid));
    }

    public function advs($request, $subjects, $cid = [], $sid, $postUrl){

        $show_type = mAdv::SHOW_TYPE;
        if(!$sid){
            $show_type = [
                mAdv::SHOW_TYPE_2 => mAdv::SHOW_TYPE[mAdv::SHOW_TYPE_2]
            ];
        }
        $category = mCategory::getAllByWhere(['status'=>mCategory::STATUS_OPEN],['id','title','parent_id']);
        $categorys = [];
        $cid = array_filter($cid);
        if (!empty($category)) {
            foreach ($category as &$_v) {
                if($_v['parent_id'] == 0){
                    $categorys['parent'][$_v['id']] = $_v['title'];
                    if(!empty($cid) && !in_array($_v['id'], $cid)){
                        unset($categorys['parent'][$_v['id']]);
                    }
                }else if(isset($categorys['parent'][$_v['parent_id']])){
                    $categorys['son'][$_v['id']] = $_v['title'];
                    if(!empty($cid) && (!in_array($_v['id'], $cid) && !in_array($_v['parent_id'], $cid))){
                        unset($categorys['son'][$_v['id']]);
                    }
                }
            }
        }
        if(!isset($categorys['parent']) || !isset($categorys['son']) || empty($subjects)) {
            //如果没有一级二级分类或者缺少主题，无法创建广告位
            unset($show_type);
        }
        //获取卡片名称
        $groupTitle = [];
        $groupTitleWhere = [
            'group_title[!]'=>'',
            'status[!]' => mCategory::STATUS_DELETE,
            'GROUP' => 'group_title'
        ];
        if($sid > 0) {
            $groupTitleWhere['sid'] = $sid;
        }
        $groupTitle = mAdv::getAllByWhere($groupTitleWhere, ['group_title', 'sort']);


        if(!empty($request['AND']['id'])){
            $data = mAdv::getOneByWhere(['id'=>$request['AND']['id']]);
            $data['link'] = [
                'link_type'=> $data['link_type'],
                'link_params'=> $data['link_params'],
                'link_url'=> $data['link_url'],
            ];
            $id = $request['AND']['id'];
        }else{
            $data = [];
            $id = 0;
        }
        $dataJsons = [
            'rela_id' => $data['rela_id'],
            'show_type' => $data['show_type'],
        ];
        $dataJson = json_encode($dataJsons, true);
        if(!empty($groupTitle)){
            $groupTitleHas = 1;
        }else{
            $groupTitleHas = 0;
        }

        $script =
            <<<SCRIPT
      var data_json = $.parseJSON('{$dataJson}');
      var groupTitle = {$groupTitleHas};
      var cur_id = {$id};
      var showtype = $('.show_type');
      var category_1 = $('input.category_1');
      var category_2 = $('input.category_2');
      var side = category_2.parents('.form-group').next('.form-group');
      var name = $('#name').parents('.form-group');
      var is_point = $('.is_point').parents('.form-group');
      var group_title1 = $('.group_title1').parents('.form-group');
      var group_title2 = $('.group_title2').parents('.form-group');
      var select_group = $('.select_group').parents('.form-group');
      var font_color = $('.font_color').parents('.form-group');
      
      category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      side.hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();

      if(cur_id > 0){
          side.show();
          name.show();
          is_point.hide();
          select_group.hide();
          group_title1.hide();
          font_color.hide();
          var cid = data_json.rela_id.split(',');
          if(data_json.show_type == 4006){  
              $.each(category_2, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').show();
              name.hide();
              font_color.show();
          }else if(data_json.show_type == 4007){
              $.each(category_1, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').show();
              category_2.parents('.form-group').hide();
              side.hide();
          }else if(data_json.show_type == 4008){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }else if(data_json.show_type == 4009){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }else if(data_json.show_type == 4010){
              select_group.show();
              //group_title1.hide();
              //group_title2.show();
              if(groupTitle > 0){
                  group_title1.hide();
                  group_title2.show();
              }else{
                  group_title1.show();
                  group_title2.hide();
              }
          }else if(data_json.show_type == 4011){
              is_point.show();
          }  
          
      }else{
//          $('input.link_type').first().iCheck('check');
//          $('input.link').val($('input.link_type').first().val());
      }
      
      
//       $('input.link_type').on('ifChecked ifUnchecked', function(event) {
//           if (event.type == 'ifChecked'){
//            $('input.link').val($(this).val());
//           }
//        });
   
        showtype.on('select2:select', function (e) { 

              side.show();
              name.show();
              is_point.hide();
              select_group.hide();
              group_title1.hide();
              group_title2.hide();
              font_color.hide();
              var data = e.params.data.id;
 if(data == 4006){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').show();
                  name.hide();
                  font_color.show();
              }else if(data == 4007){
                  category_1.parents('.form-group').show();
                  category_2.parents('.form-group').hide();
                  side.hide();
              }else if(data == 4008){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }else if(data == 4009){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }else if(data == 4010){
                  select_group.show();
                  if(cur_id > 0 && groupTitle > 0){
                      group_title1.hide();
                      group_title2.show();
                  }else{
                      group_title1.show();
                      group_title2.hide();
                  }
              }else if(data == 4011){
                  is_point.show();
              }else if(data == 4012){
                        category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();
              }else if(data == 4013){
                        category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();
              }
        });
       
        
        $('.select_group').on('ifChecked ifUnchecked', function(event) {
           if (event.type == 'ifChecked' && event.currentTarget.defaultValue==1){
                group_title1.show();
                group_title2.hide();
                $('input.sort').parents('.form-group').show();
           }else{
                group_title1.hide();
                group_title2.show();
                $('input.sort').parents('.form-group').hide();
           }
           if(cur_id > 0){
               $('input.sort').parents('.form-group').show();
            }
        });
       
      

SCRIPT;


        Admin::script($script);
        //Admin::script('imgUpload.one();');
        $form = new Form($data);
        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->select('show_type', '位置')
            ->options($show_type)
            ->setWidth(4, 2)
            ->required('不能为空');
        ;

        $form->checkbox('category_1','关联一级分类')->options(isset($categorys['parent'])?$categorys['parent']:[]);
        if(isset($categorys['son'])) {
            $form->checkbox('category_2', '关联二级分类')->options(isset($categorys['son']) ? $categorys['son'] : []);
        }
        $form->select('sid', '关联主题')->options($subjects)->setWidth(4, 2);

        $groupTitles = array_column($groupTitle, 'group_title', 'group_title');
        if(!empty($groupTitles)) {
            if(isset($request['AND']['id'])) {
                $form->radio('select_group', '是否创建内容卡片')->options([1 => '是', 0 => '否'])->default(0)->setWidth(4, 2);
            }else{
                $form->radio('select_group', '是否创建内容卡片')->options([1 => '是', 0 => '否'])->default(1)->setWidth(4, 2);
            }
        }else{
            $form->radio('select_group', '是否创建内容卡片')->options([1 => '是'])->default(1)->setWidth(4, 2);
        }
        $form->select('group_title2', '选择内容卡片')->options($groupTitles)->default(function ()use($data){
            return isset($data['group_title'])?$data['group_title']:'';
        })->setWidth(4, 2);
        $form->text('group_title1', '创建内容卡片')->setWidth(4, 2);
        //$form->text('sort', '权重')->setWidth(4, 2);


        $form->text('name', '名称')->setWidth(4, 2);
        $form->color('font_color', '字体景色')->setWidth(4, 2);
        $form->radio('is_point', '背景透明')->options([0=>'否',1=>'是'])->setWidth(4, 2);
        $form->linkSelect('link');
        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->imgUpload('pic_id', '封面');
        $form->number('pos', '位置')->help('主题页住友分享和主题页好物推荐使用');
        $form->text('obj_id', '内容id')->help('主题页住友分享和主题页好物推荐使用,包含wiki');
        if(isset($request['AND'])){
            foreach($request['AND'] as $_k=>&$_v){
                if(!empty($_v)){
                    $_k = str_replace('[>=]','', $_k);
                    $_k = str_replace('[<]','', $_k);
                    $url_request[] =  $_k.'='.$_v;
                }
            }
            $url_request = implode('&', $url_request);
            $form->action($postUrl.'?'.$url_request);
        }else{
            $form->action($postUrl);
        }

        return $form->render();
    }

    public function advsList($request, $sid){
        //列表获取搜索条件
        $get = $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';
        //按名称搜索时
        if(!empty($request['AND']['name'])){
            $sids = mSubject::getOneByWhere(['name'=>$request['AND']['name']],'id');
            if($sids){
                $request['OR'] = [
                    'sid'=> $sids,
                    'name'=> $request['AND']['name'],
                ];
                unset($request['AND']['name']);
                if(empty($request['AND'])){
                    unset($request['AND']);
                }
            }
        }
        if($sid > 0) {
            if (isset($request['AND'])) {
                $request['AND']['sid'] = $sid;
            } else {
                $request['sid'] = $sid;
            }
        }

        $adv = sMain::getAdv($request);
        $gridModel = new pGridDataModel(
            $adv['list'],
            $adv['total'],
            [
                'perPage' => self::PAGE_SIZE,
            ]
        );

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($get,$sid) {
            //$grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->between('date_time', '资源时间')->datetime()->condition($_GET);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('show_type', '资源位置')->select(mAdv::SHOW_TYPE);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '名称')->placeholder('请输入名称');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('group_title', '内容卡片标题')->placeholder();
                });
            });

            $grid->fixColumns(1,-2);

            $grid->column('id', 'id');
            $grid->column('rela_id', '关联分类');
            $grid->column('sid', '关联主题');
            $grid->column('show_type', '资源位置')->display(function(){
                return mAdv::SHOW_TYPE[$this->show_type];
            });
            $grid->column('name', '名称')->display(function(){
                if(!empty($this->name)) {
                    return '<p style="color:' . $this->font_color . ';">' . $this->name . '</p>';
                }else{
                    return '<p style="color:' . $this->font_color . ';">暂空</p>';
                 }

            });
            $grid->column('group_title', '内容卡片');
            $grid->column('is_point', '背景是否透明')->display(function(){
                if($this->is_point) {
                    return '是';
                }else{
                    return '否';
                }
            });
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('sort', '权重');
            //$grid->column('link', '链接')->limit(30);
            $grid->column('link', '链接信息')->linkSelect();

            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions)use($get, $sid){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                if($actions->row->status < 2) {
                    $actions->append("<a href=\"/admin/decoration/adv/".$sid."/create?id=" . $actions->row->id . "\" class=\"btn btn-primary\">编辑</a>");
                    $actions->append("<a href=\"/admin/decoration/adv/del/" . $actions->row->id . '/' . $sid . $get . "\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //单独创建分类首页banner广告位
    public function createAdv(){
        $adv = mCategory::getOneByWhere(['title'=>'推荐'],'id');

        return redirect('/admin/decoration/category/'.$adv.'/edit/adv/create');
    }


    //获取广告位
    public function _getShowtype($request, $showType = 0){
        if(isset($request['AND']['rela_id']) && !isset($request['AND']['id'])){
            $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$request['AND']['rela_id'].',rela_id)';
            $relaId = mAdv::query($sql)->fetchAll();
            $request['AND']['id'] = array_column($relaId, 'id');
            unset($request['AND']['rela_id']);
        }
        if($showType>0) {
            $request['AND']['show_type'] = $showType;
        }
        if(empty($request['AND'])){
            unset($request['AND']);
        }
        $request['ORDER'] = ['id' => 'DESC'];
        $count = mAdv::getCount($request);
        $data = mAdv::getAllByWhere($request);
        $gridModel = new pGridDataModel($data, $count, [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($showType) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();

            if($showType>0){
                $grid->disableFilter();
            }else {
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('date_time', '资源时间')->datetime()->condition($_GET);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('show_type', '资源位置')->select(mAdv::SHOW_TYPE);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('name', '名称')->placeholder('请输入名称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('group_title', '内容卡片标题')->placeholder();
                    });
                });
                $grid->fixColumns(0, -1);
            }

            $grid->column('id')->sort();;
//            $grid->column('sid_name', '关联主题');
//            $grid->column('show_type', '资源位置')->display(function(){
//                return mAdv::SHOW_TYPE[$this->show_type];
//            });
//            $grid->column('name', '名称')->display(function(){
//                if(!empty($this->name)) {
//                    return '<p style="color:' . $this->font_color . ';">' . $this->name . '</p>';
//                }else{
//                    return '<p style="color:' . $this->font_color . ';">暂空</p>';
//                }
//
//            });
//            $grid->column('group_title', '内容卡片');
//            $grid->column('is_point', '背景是否透明')->display(function(){
//                if($this->is_point) {
//                    return '是';
//                }else{
//                    return '否';
//                }
//            });
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('pos', '轮播位置');

//            if (in_array($showType, [4012, 4013])) {
//                $grid->column('pos', '位置');
//                $grid->column('obj_id', '内容/wiki id');
//            }

            if($showType > 0) {
                $grid->column('link', '链接')->limit(30);
            }else {
                $grid->column('link', '链接信息')->linkSelect();
            }

            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();

                if($actions->row->status >= 2) {
                    $actions->disableEdit();
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

}